
var prefix = ctx +"module/survey/record";
$(function() {
    load();
});
function load(){
    layui.use(['form','laydate','table'], function() {
        var form = layui.form , table = layui.table, laydate = layui.laydate, element = layui.element;//载入table模块

        laydate.render({
            elem: '#begin_date',
            isInitValue: false,
        });
        laydate.render({
            elem: '#end_date',
            isInitValue: false,
        });


        var searchParams = {};
        searchParams['search_eq_surveyId']=$('#surveyId').val();
        searchParams['search_eq_townId']=$('#townId').val();
        searchParams['search_eq_villageId']=$('#villageId').val();
        searchParams['search_like_keyword']=$('#keyword').val();

        if($('#begin_date').val() !== "" && $('#end_date').val() !== ""){
            searchParams['begin_date']=$('#begin_date').val() + " 00:00:00";
            searchParams['end_date']=$('#end_date').val()+ " 23:59:59";
        }
        form.on('select(townId)', function (data) {
            console.log('townId',data.value);
            getVillages(data.value,form)
        });

        //初始化table
        table.render({
            elem: '#exampleTable',//承载数据的table Id
            url: prefix + "/list",//请求数据连接
            toolbar: '#toolbarDemo',
            cellMinWidth: 80,//全局定义所有常规单元格的最小宽度（默认：60）
            even: true,//是否开启隔行变色
            loading:true,//是否显示加载条
            // height: 'full-75',
            where :{
                searchParams:searchParams,
                sorts:{"id":"desc"}
            },
            //page: true,//是否分页
            page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: [ 'prev', 'page', 'next', 'skip', 'count','limit'] //自定义分页布局
            },
            defaultToolbar: false,
            cols: [[
                {type:'numbers',title: '序号', width:'5%'},
                { field : 'townName',  title : '所属乡镇',  align : 'center', },
                { field : 'villageName',  title : '所属村居', align : 'center', },
                { field : 'roomNo',  title : '户号', align : 'center', },
                { field : 'holderName',  title : '房主姓名', align : 'center', },
                { field : 'holderPhone',  title : '房主电话', align : 'center', },
                { field : 'managerName',  title : '包保人姓名', align : 'center', },
                { field : 'managerPhone',  title : '包保人电话', align : 'center', },
                { field : 'createTime',  title : '上报时间', align : 'center', },
                { title: '操作', minWidth: 100, templet: '#currentTableBar', fixed: "right", align: "center"}
            ]],
            id: 'currentTableId'//表格Id
        });
        /**
         * 操作栏tool  监听事件
         */
        table.on('tool(currentTableFilter)', function (obj) {
            if (obj.event === 'edit') {  // 监听添加操作
                console.log('obj',obj.data.id);
                edit(obj.data.id);
            } else if (obj.event === 'delete') {  // 监听删除操作
                console.log('obj',obj.data.id);
                remove(obj.data.id);
            } else if (obj.event === 'info') {  // 监听删除操作
                console.log('obj',obj.data.id);
                goInfo(obj.data.id);
            }
        });
        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            reLoad();
            return false;
        });

        /**
         * 操作栏tool  监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                add();
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId'), data = checkStatus.data;
                layer.alert(JSON.stringify(data));
            }else if (obj.event === 'back') {  // 监听添加操作
                goBack();
            } else if(obj.event === 'export'){
                exportExcel();
            }
        });
    });
}

function goInfo(id) {
    var surveyId =  $('#surveyId').val();
    window.location.href = prefix + '/info/'+ surveyId +'/'+ id
}


function exportExcel(){
    var survey_id = $("#surveyId").val();
    var town_id = $("#townId").val();
    var begin_date = $("#begin_date").val();
    var end_date = $("#end_date").val();

    if(begin_date == undefined || begin_date == ''){
        layer.msg('请选择开始时间和结束时间');
        return ;
    }
    if(end_date == undefined || end_date == ''){
        layer.msg('请选择开始时间和结束时间');
        return ;
    }

    // 将字符串转换为日期格式
    var d1 = new Date(begin_date);
    var d2 = new Date(end_date);

    // 获取两个日期的时间戳（单位：毫秒）
    var timeDiff = Math.abs(d2.getTime() - d1.getTime());

    // 计算相差的天数并返回结果
    var days = Math.ceil(timeDiff / (1000 * 3600 * 24));
    console.log('days',days);
    if(days > 7){
        layer.msg('查询日期不能超过7天');
        return ;
    }


    if(town_id == ''){
        layer.msg('请选择乡镇');
    }else{
        window.location.href = ctx + 'module/survey/record/exportExcel?survey_id='
            + survey_id + '&town_id=' + town_id + "&begin_date=" + begin_date + "&end_date="+ end_date;
    }
}


function getVillages(townId,form) {
    $.ajax({
        url : ctx +"module/citizen/villages",
        type : "post",
        data:{
            townId:townId
        },
        success : function(r) {
            console.log('r',r)
            if (r.code==0) {
                console.log("villages",r.villages);

                var villages = r.villages;
                if (villages.length > 0) {
                    $('#villageId').empty();
                    $('#villageId').append(new Option('请选择村居', ''));
                    for (var i = 0; i < villages.length; i++) {
                        $('#villageId').append(new Option(villages[i].townName, villages[i].id));
                    }
                } else {
                    $('#villageId').empty();
                    $('#villageId').append(new Option('暂无村居', ''));
                }
                form.render("select");
            }
        }
    });
}


function goBack(){
    window.location.href = ctx + 'module/survey/';
}


function reLoad() {
    var searchParams = {};
    searchParams['search_eq_surveyId']=$('#surveyId').val();
    searchParams['search_eq_townId']=$('#townId').val();
    searchParams['search_eq_villageId']=$('#villageId').val();
    searchParams['search_like_keyword']=$('#keyword').val();

    if($('#begin_date').val()!="" && $('#end_date').val()!=""){
        searchParams['begin_date']=$('#begin_date').val() + " 00:00:00";
        searchParams['end_date']=$('#end_date').val()+ " 23:59:59";
    }

    layui.use(['table'], function() {
        var table = layui.table;//载入table模块

        var  page = $(".layui-laypage-skip").find("input").val() //当前页码值
        console.log('page',page)
        table.reload('currentTableId', {
            page: {curr: page}
            , where: {
                searchParams: searchParams
            }
        }, 'data');
    });
}


function add() {
	var index = layer.open({
        type : 2,
        title : '增加',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '500px', '300px' ],
        content : prefix + '/add' // iframe的url
    });
	// layer.full(index);
}

function edit(id) {
	var index = layer.open({
        type : 2,
        title : '编辑',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '500px', '300px' ],
        content : prefix + '/edit/' + id // iframe的url
    });
	// layer.full(index);
}
function remove(id) {
    layer.confirm('确定要删除选中的记录？', {
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : prefix+"/remove",
            type : "post",
            data : {
                'id' : id
            },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    reLoad();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}


